import { LoginResponse, Token } from "@/types/data"
import { http } from "@/utils/http"
import { clearToken, setToken } from "@/utils/token"
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit"
import { AxiosError } from "axios"
const initialState: Token = {
    // 登录token
    token: '',
    // 刷新token，在 token 过期后，用来换取新的 token
    refresh_token: '',
}


/**
 * 登录
 */
export const login = createAsyncThunk('login/login', async (loginData: { mobile: string; code: string }, { rejectWithValue }) => {
    try {
        const res = await http.post<LoginResponse>('/authorizations', loginData)
        setToken(res.data.data)
        // 存储到redux
        return res.data.data
    } catch (error) {
        const err = error as AxiosError<{ data: null; message: string }>
        return rejectWithValue(err.response?.data);
    }
})

/**
 * 退出登录
 */
export const logout = createAsyncThunk('login/logout', () => {
    clearToken();
    return initialState;
})

/**
 * 发送验证码
 */
export const sendCode = createAsyncThunk('login/sendCode', async (mobile: string) => {
    await http.get(`/sms/codes/${mobile}`)
})

const loginSlice = createSlice({
    name: 'login',
    initialState,
    //  定义的action。由于内置了immutable插件，可以直接使用赋值的方式进行数据的改变，不需要每一次都返回一个新的state数据。
    reducers: {
        /**
         * 更新token
         * @param state 数据源
         * @param action 更新数据源的操作
         * @returns 
         */
        updateToken: (state, action: PayloadAction<Token>) => {
            return action.payload
        }
    },
    extraReducers: builder => {

        // 处理登录时的状态
        builder.addCase(login.fulfilled, (state, action) => {
            return action.payload;
        })

        // 退出
        builder.addCase(logout.fulfilled, (state, action) => {
            // action.payload 就是 initialState 默认的状态值
            return action.payload
        })
    }
})

export const { updateToken } = loginSlice.actions
export default loginSlice.reducer